package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fxl
 * @since 2025-05-12
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Override
    public Result queryTypeList() {
        // 1.从redis中查询
        String shopType = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_TYPE_List);
        
        if (StrUtil.isNotBlank(shopType)) {
            // 2.存在，直接返回数据
            List<ShopType> shopTypeList1 = JSONUtil.toList(shopType, ShopType.class);
            return Result.ok(shopTypeList1);
        }
        // 3.不存在，查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        // 4.数据库中不存在，返回错误
        if (shopTypeList == null) {
            return Result.fail("店铺列表不存在！");
        }
        // 5.数据库中存在，写入redis
        stringRedisTemplate.opsForValue().set(
                RedisConstants.SHOP_TYPE_List,
                JSONUtil.toJsonStr(shopTypeList)
        );
        // 6.返回数据
        return Result.ok(shopTypeList);
    }
}
